/**
 * Search Store
 * 负责管理search相关的状态和数据处理
 */

import { observable, action  } from 'mobx-miniprogram';

// 搜索历史的存储键
const SEARCH_HISTORY_KEY = 'searchHistory';

// 搜索模块Store
export const searchStore = observable({
  // 搜索关键词
  keyword: '',
  
  // 搜索历史
  searchHistory: [],
  
  // 搜索类型
  searchType: 'all', // all, project, task, knowledge, news, contact
  
  // 搜索结果
  results: {
    project: [],
    task: [],
    knowledge: [],
    news: [],
    contact: [],
    customer: []
  },
  
  // 搜索状态
  status: {
    searching: false,
    error: null,
    lastSearchTime: null
  },
  
  // 搜索统计
  statistics: {
    total: 0,
    byType: {}
  },
  
  // 高级搜索过滤条件
  advancedFilter: {
    dateRange: null,
    creator: '',
    department: '',
    status: '',
    category: ''
  },
  
  // 热门搜索关键词
  hotKeywords: ['项目管理', '待办事项', '研发流程', '会议记录', '客户联系'],
  
  // 计算属性：获取总结果数
  get totalResults() {
    let count = 0;
    Object.keys(this.results).forEach(key => {
      count += this.results[key].length;
    });
    return count;
  },
  
  // 计算属性：获取扁平化的全部结果
  get allResults() {
    const all = [];
    
    Object.keys(this.results).forEach(type => {
      this.results[type].forEach(item => {
        all.push({
          ...item,
          resultType: type
        });
      });
    });
    
    return all;
  },
  
  // 计算属性：获取按类型分组的结果
  get groupedResults() {
    const grouped = {};
    
    Object.keys(this.results).forEach(type => {
      if (this.results[type].length > 0) {
        grouped[type] = this.results[type];
      }
    });
    
    return grouped;
  },
  
  // 计算属性：获取热门搜索词
  get topHotKeywords() {
    return this.hotKeywords.slice(0, 5);
  },
  
  // Action: 设置搜索关键词
  setKeyword: action(function(keyword) {
    this.keyword = keyword;
  }),
  
  // Action: 设置搜索类型
  setSearchType: action(function(type) {
    this.searchType = type;
  }),
  
  // Action: 记录搜索历史
  addToHistory: action(function(keyword) {
    // 初始化检查
    if (!Array.isArray(this.searchHistory)) {
      this.searchHistory = [];
    }
    
    // 检查是否已存在
    const index = this.searchHistory.indexOf(keyword);
    if (index >= 0) {
      // 已存在，则删除原有的
      this.searchHistory.splice(index, 1);
    }
    
    // 添加到最前面
    this.searchHistory.unshift(keyword);
    
    // 最多保留20条
    if (this.searchHistory.length > 20) {
      this.searchHistory.pop();
    }
    
    // 保存到本地存储
    wx.setStorageSync(SEARCH_HISTORY_KEY, this.searchHistory);
  }),
  
  // Action: 清空搜索历史
  clearHistory: action(function() {
    this.searchHistory = [];
    wx.removeStorageSync(SEARCH_HISTORY_KEY);
  }),
  
  // Action: 获取特定类型的搜索历史
  getHistoryByType: action(function(type) {
    if (!Array.isArray(this.searchHistory)) {
      return [];
    }
    
    return this.searchHistory.filter(item => 
      typeof item === 'string' && item.startsWith(type + '_')
    ).map(item => item.substring(type.length + 1));
  }),
  
  // Action: 设置高级搜索过滤条件
  setAdvancedFilter: action(function(filter) {
    this.advancedFilter = {...this.advancedFilter, ...filter};
  }),
  
  // Action: 清空高级搜索过滤条件
  clearAdvancedFilter: action(function() {
    this.advancedFilter = {
      dateRange: null,
      creator: '',
      department: '',
      status: '',
      category: ''
    };
  }),
  
  // Action: 设置搜索结果
  setResults: action(function(results) {
    this.results = {...this.results, ...results};
    this.updateStatistics();
    this.status.lastSearchTime = dayjs();
  }),
  
  // Action: 设置单个类型的搜索结果
  setResultByType: action(function(type, data) {
    if (this.results[type] !== undefined) {
      this.results[type] = data;
      this.updateStatistics();
    }
  }),
  
  // Action: 清空搜索结果
  clearResults: action(function() {
    Object.keys(this.results).forEach(key => {
      this.results[key] = [];
    });
    this.updateStatistics();
  }),
  
  // Action: 设置搜索中状态
  setSearching: action(function(searching) {
    this.status.searching = searching;
    
    if (!searching) {
      this.status.lastSearchTime = dayjs();
    }
  }),
  
  // Action: 设置搜索错误
  setError: action(function(error) {
    this.status.error = error;
    this.status.searching = false;
  }),
  
  // Action: 更新搜索统计
  updateStatistics: action(function() {
    const byType = {};
    let total = 0;
    
    Object.keys(this.results).forEach(type => {
      byType[type] = this.results[type].length;
      total += this.results[type].length;
    });
    
    this.statistics = {
      total,
      byType
    };
  }),
  
  // Action: 初始化搜索历史
  initSearchHistory: action(function() {
    try {
      const history = wx.getStorageSync(SEARCH_HISTORY_KEY);
      if (history && Array.isArray(history)) {
        this.searchHistory = history;
      } else {
        this.searchHistory = [];
      }
    } catch (e) {
      console.error('Failed to get search history from storage', e);
      this.searchHistory = [];
    }
  }),
  
  // Action: 删除单条历史记录
  removeHistoryItem: action(function(keyword) {
    const index = this.searchHistory.indexOf(keyword);
    if (index >= 0) {
      this.searchHistory.splice(index, 1);
      wx.setStorageSync(SEARCH_HISTORY_KEY, this.searchHistory);
    }
  })
}); 